# Copyright 2009 Lee Harr
#
# This file is part of Acromania.
#
# Acromania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Acromania is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Acromania.  If not, see <http://www.gnu.org/licenses/>.


from twisted.words.protocols.irc import IRCClient

import amgame
import conf
import colors

class AMIRC(IRCClient, amgame.CMix):
    nickname = conf.botnick
    channels = conf.channels
    players = {}

    def message(self, *args, **kw):
        color = kw.get('color', True)
        strs = map(str, args)
        msg = ' '.join(strs)
        msg = msg % colors.irc
        user = kw.get('user', None)
        self.notice(user, msg)

    def signedOn(self):
        """Called when bot has succesfully signed on to server."""
        self.join(self.factory.channel)
        self.gameserver = self.factory.gameserver

    def joined(self, channel):
        """This will get called when the bot joins the channel."""
        print "[I have joined %s]" % channel

    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]
        print "<%s> %s" % (user, msg)
        player = self.players.get(user, None)
        if player is not None:
            self.command(msg, player)

    def userJoined(self, user, channel):
        user = user.split('!', 1)[0]
        print '%s joined %s' % (user, channel)
        player = self.gameserver.join(self)
        player.user = user
        self.players[user] = player

    def userLeft(self, user, channel):
        user = user.split('!', 1)[0]
        print '%s left %s' % (user, channel)

    def change_name(self, player, name):
        pass

    def userQuit(self, user, quitMessage):
        self.userLeft(user, self.factory.channel)

    def game_over(self, player):
        player.message('Game over. Type /msg %s new to start again.' % self.nickname)

    def help(self, player):
        'Show HELP file.'

        lines = open('HELP.irc').readlines()

        for line in lines:
            player.message(line.rstrip())

    def rules(self, player):
        'Show RULES file.'

        lines = open('RULES').readlines()

        for line in lines:
            line = line.replace('/', '/msg acrobot ')
            player.message(line.rstrip())

